//
//  NSObject+FCUrlPathGet.m
//  Pods
//
//  Created by WJC on 2020/12/30.
//

#import "NSObject+FCUrlPathGet.h"

#import "NSDictionary+setDic.h"
#import "UIImage+Extension.h"
#import <objc/runtime.h>
#import "FCURLLocalBaseSave.h"

#import "FCAlertToastView.h"
@implementation upLoadModel
-(void)setUploadType:(INFIUploadType)uploadType{
    _uploadType = uploadType;
    switch (uploadType) {
        case INFIUploadTypeImg:
            self.ext = @".png";
            self.mimeType = @"image/png";
            break;
        case INFIUploadTypeVideo:
            self.ext = @".mp4";
            self.mimeType = @"video/mp4";
            break;
        case INFIUploadTypeVoice:
            self.ext = @".AAC";
            self.mimeType = @"audio/aac";
        default:
            self.ext = @"";
            self.mimeType = @"text/html";
            break;
    }
}
@end
@implementation NSObject (FCUrlPathGet)
static const char *successKey = "successKey";
-(void)setUrlPath:(NSString *)urlPath{
    if ([urlPath isKindOfClass:[NSString class]] && [[urlPath substringToIndex:1] isEqual:@"/"]) {
        urlPath = [urlPath substringFromIndex:1];
    }
    objc_setAssociatedObject(self, @selector(urlPath), urlPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)urlPath{
    return objc_getAssociatedObject(self, @selector(urlPath));
}
-(NSString *)requestStrMJClass{
    return objc_getAssociatedObject(self, @selector(requestStrMJClass));
}
-(void)setRequestStrMJClass:(NSString *)requestStrMJClass{
    objc_setAssociatedObject(self, @selector(requestStrMJClass), requestStrMJClass, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
}
-(NSObject *)mjClass{
    return objc_getAssociatedObject(self, @selector(mjClass));
}
-(void)setMjClass:(NSObject *)mjClass{
    objc_setAssociatedObject(self, @selector(mjClass), mjClass, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)setFilterError:(bool)filterError{
    objc_setAssociatedObject(self, @selector(filterError), @(filterError), OBJC_ASSOCIATION_ASSIGN);
}
-(bool)filterError{
    return objc_getAssociatedObject(self, @selector(filterError));
}
-(void)setNotJson:(bool)notJson{
    objc_setAssociatedObject(self, @selector(notJson), @(notJson), OBJC_ASSOCIATION_ASSIGN);
}
-(bool)notJson{
    return objc_getAssociatedObject(self, @selector(notJson));
}
-(void)setPrintSuccess:(bool)printSuccess{
    objc_setAssociatedObject(self, @selector(printSuccess), @(printSuccess), OBJC_ASSOCIATION_ASSIGN);
}
-(bool)printSuccess{
    return objc_getAssociatedObject(self, @selector(printSuccess));
}
-(void)setIndexGet:(NSInteger)indexGet{
    objc_setAssociatedObject(self, @selector(indexGet), @(indexGet), OBJC_ASSOCIATION_ASSIGN);
}
-(NSInteger)indexGet{
    return objc_getAssociatedObject(self, @selector(indexGet));
}
-(void)setRequestData:(NSDictionary *)requestData{
    objc_setAssociatedObject(self, @selector(requestData), requestData, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSDictionary *)requestData{
    return objc_getAssociatedObject(self, @selector(requestData));
}
-(void)setRequestHeaderData:(NSDictionary *)requestHeaderData{
    objc_setAssociatedObject(self, @selector(requestHeaderData), requestHeaderData, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSDictionary *)requestHeaderData{
    return objc_getAssociatedObject(self, @selector(requestHeaderData));
}
-(void)upRequestDataBaseWithSuccess:(NSString*)success andError:(NSString *)errorReponse{
    FCURLLocalBaseSave *save = [FCURLLocalBaseSave new];
    save.path = self.urlPath;
    save.mjClass = [FCURLLocalBaseSave new];
    save.request = self.requestData.printfJson;
    save.error =errorReponse;
    save.success = success;
    [save insertNewDataBaseWithDic:save.mj_keyValues];
    
}
-(void)getRequestWithBlock:(requestSuccetionActionBlock)success{
    NSString *urlStr;
    if ([self.urlPath isUrl]) {
        urlStr = self.urlPath;
    }else{
        if (self.urlPath) {
            urlStr = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl],self.urlPath];
        }
    }
        NSMutableDictionary *requestData = [NSMutableDictionary dictionaryWithDictionary:self.requestData];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    if (success) {
    //检查地址中是否有中文
   urlStr = [NSURL URLWithString:urlStr] ? urlStr : [self strUTF8Encoding:urlStr];
    AFHTTPSessionManager *manager = [self getAFManager];
        if([self isKindOfClass:[UIButton class]]){
            ((UIButton*)self).enabled = NO;
        }
        [manager GET:urlStr parameters:requestData headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            if([self isKindOfClass:[UIButton class]]){
                ((UIButton*)self).enabled = YES;
            }
        });
        if (self.notJson) {
            if (success) {
                success(responseObject);
                return;
            }
        }
       id obj = [NSDictionary changeType:responseObject];
        
        if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
            NSDictionary *dic = @{
                @"url":urlStr,
                @"requestData":requestData.printfJson,
                @"reponse":((NSDictionary*)obj).printfJson
            };
            WJCLog(@"requestPrint:%@",dic.logParagraph);
            
        }
        if ([obj[@"status"] integerValue]!=0&&[obj[@"status"] integerValue]!=200&&obj[@"msg"]) {
           
            if (!self.filterError) {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",obj[@"msg"]]];
                if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]){
                    [FCAlertToastView showFailWithStatus:[NSString stringWithFormat:@"%@\n\nURL:%@ head:%@\ndata:%@",obj[@"msg"],urlStr,manager.requestSerializer.HTTPRequestHeaders,requestData] andInputEnable:NO];
                }
                
            }
            [obj checkErrorStatus:[obj[@"code"] integerValue]];
            return;
        }
        
        if (success) {
            if (obj) {
                [self saveLocalSaveWithRespon:obj];
                       }
            if(self.requestStrMJClass.length>0){
                NSArray *arr = [self.requestStrMJClass componentsSeparatedByString:@","];
                id object = [obj skipGraphQLItems];
                for (NSString *str in arr) {
                    if (!object) {
                        success(nil);
                        WJCLog(@"❌❌NSObject+KVCChangeType中requestClick数据找不到'%@'❌❌",str);
                        break;
                    }
                    if ([object isKindOfClass:[NSArray class]]) {
                        object = object[[str integerValue]];
                    }else{
                        object = object[str];
                    }
                }
                if ([object isKindOfClass:[NSArray class]]) {
                    if (self.mjClass) {
                        NSArray *arr =[[self.mjClass class] mj_objectArrayWithKeyValuesArray:object];
                        success(arr);
                    }else{
                        success(object);
                    }
                    
                }else{
                    if (self.mjClass) {
                        id obj =[[self.mjClass class] mj_objectWithKeyValues:object];
                        success(obj);
                    }else{
                        success(object);
                    }
                }
                
            }else{
                success(obj);
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self upRequestDataBaseWithSuccess:((NSDictionary*)obj).printfJson andError:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:self.urlPath object:nil];
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        if([self isKindOfClass:[UIButton class]]){
            ((UIButton*)self).enabled = YES;
        }
        if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]){
            [FCAlertToastView showFailWithStatus:[NSString stringWithFormat:@"URL:%@\n\n head:%@\ndata:%@",manager.requestSerializer.HTTPRequestHeaders,urlStr,requestData] andInputEnable:NO];
            
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshEnd" object:nil];
        if(error.userInfo[@"com.alamofire.serialization.response.error.data"]){
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:&error];
            if (!self.filterError) {
            if (dic[@"errors"]&&[dic[@"errors"] isKindOfClass:[NSArray class]]&&dic[@"errors"][0][@"message"]) {
                [SVProgressHUD showErrorWithStatus:dic[@"errors"][0][@"message"]];
            }else if ([dic isKindOfClass:[NSDictionary class]]&&dic[@"error"]) {
                [SVProgressHUD showErrorWithStatus:dic[@"error"]];
            }
            }
        }else if (error.userInfo[@"NSLocalizedDescription"]&&!self.filterError){
            [SVProgressHUD showErrorWithStatus:error.userInfo[@"NSLocalizedDescription"]];
        }
    }];
    }
}
-(void)postRequestWithBlock:(requestSuccetionActionBlock)success{
    [self postRequestWithlocalSuccessBlock:nil Block:^(id  _Nonnull obj) {
        if (success) {
            success(obj);
        }
    } andFail:^(id  _Nonnull obj) {
        
    }];
}
-(void)postRequestWithlocalSuccessBlock:(requestSuccetionActionBlock)localSuccess Block:(requestSuccetionActionBlock)success andFail:(requestSuccetionActionBlock)fail{
    NSString *urlStr;
    if ([self.urlPath isUrl]) {
        urlStr = self.urlPath;
    }else{
        if (self.urlPath) {
            urlStr = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl],self.urlPath];
        }
    }
        NSMutableDictionary *requestData = [NSMutableDictionary dictionaryWithDictionary:self.requestData];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    if (localSuccess) {
        NSArray * arr= [self getLocalCache];
        FCUrlLocalModel *model =arr.firstObject;
        if (model.data) {
            id responseObj = [NSDictionary getDicWithData:model.data];
            
            id result = nil;
            result = [NSDictionary changeType:responseObj];
            if (localSuccess) {
                if(self.requestStrMJClass.length>0){
                    NSArray *arr = [self.requestStrMJClass componentsSeparatedByString:@","];
                    for (NSString *str in arr) {
                        if (!result) {
                            localSuccess(nil);
                            WJCLog(@"❌❌NSObject+KVCChangeType中requestClick数据找不到'%@'❌❌",str);
                            break;
                        }
                        if ([result isKindOfClass:[NSArray class]]) {
                            result = result[[str integerValue]];
                        }else{
                            result = result[str];
                        }
                    }
                    
                    if ([result isKindOfClass:[NSArray class]]) {
                        if (self.mjClass) {
                            localSuccess([[self.mjClass class] mj_objectArrayWithKeyValuesArray:result]);
                        }else{
                            localSuccess(result);
                        }
                        
                    }else{
                        if (self.mjClass) {
                            localSuccess([[self.mjClass class] mj_objectWithKeyValues:result]);
                        }else{
                            localSuccess(result);
                        }
                    }
                    
                }else{
                    if (self.mjClass) {
                        localSuccess([[self.mjClass class] mj_objectWithKeyValues:result]);
                    }else{
                        localSuccess(result);
                    }
                }
            }
        }
    }
    if (success) {
    //检查地址中是否有中文
   urlStr = [NSURL URLWithString:urlStr] ? urlStr : [self strUTF8Encoding:urlStr];
    AFHTTPSessionManager *manager = [self getAFManager];
        if([self isKindOfClass:[UIButton class]]){
            ((UIButton*)self).enabled = NO;
        }
        [manager POST:urlStr parameters:requestData headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
            if([self isKindOfClass:[UIButton class]]){
                ((UIButton*)self).enabled = YES;
            }
        });
        if (self.notJson) {
            if (success) {
                success(responseObject);
                return;
            }
        }
       id obj = [NSDictionary changeType:responseObject];
        
        if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
            NSDictionary *dic = @{
                @"url":urlStr,
                @"requestData":requestData.printfJson,
                @"reponse":((NSDictionary*)obj).printfJson
            };
            WJCLog(@"requestPrint:%@",dic.logParagraph);
            
        }
        if ([obj[@"status"] integerValue]!=0&&[obj[@"status"] integerValue]!=200&&obj[@"msg"]) {
           
            if (!self.filterError) {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",obj[@"msg"]]];
                if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]){
                    [FCAlertToastView showFailWithStatus:[NSString stringWithFormat:@"%@\n\nURL:%@ head:%@\ndata:%@",obj[@"msg"],urlStr,manager.requestSerializer.HTTPRequestHeaders,requestData] andInputEnable:NO];
                }
                
            }
            [obj checkErrorStatus:[obj[@"code"] integerValue]];
            if (fail) {
                fail(obj);
            }
            return;
        }
        
        if (success) {
            if (obj) {
                [self saveLocalSaveWithRespon:obj];
                       }
            if(self.requestStrMJClass.length>0){
                NSArray *arr = [self.requestStrMJClass componentsSeparatedByString:@","];
                id object = [obj skipGraphQLItems];
                for (NSString *str in arr) {
                    if (!object) {
                        success(nil);
                        WJCLog(@"❌❌NSObject+KVCChangeType中requestClick数据找不到'%@'❌❌",str);
                        break;
                    }
                    if ([object isKindOfClass:[NSArray class]]) {
                        object = object[[str integerValue]];
                    }else{
                        object = object[str];
                    }
                }
                if ([object isKindOfClass:[NSArray class]]) {
                    if (self.mjClass) {
                        NSArray *arr =[[self.mjClass class] mj_objectArrayWithKeyValuesArray:object];
                        success(arr);
                    }else{
                        success(object);
                    }
                    
                }else{
                    if (self.mjClass) {
                        id obj =[[self.mjClass class] mj_objectWithKeyValues:object];
                        success(obj);
                    }else{
                        success(object);
                    }
                }
                
            }else{
                success(obj);
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self upRequestDataBaseWithSuccess:((NSDictionary*)obj).printfJson andError:nil];
                if(self.urlPath.length>1){
                    [[NSNotificationCenter defaultCenter] postNotificationName:self.urlPath object:nil];
                }
            });
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        if([self isKindOfClass:[UIButton class]]){
            ((UIButton*)self).enabled = YES;
        }
        if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]){
            [FCAlertToastView showFailWithStatus:[NSString stringWithFormat:@"URL:%@\n\n head:%@\ndata:%@",manager.requestSerializer.HTTPRequestHeaders,urlStr,requestData] andInputEnable:NO];
            
        }
        if (fail) {
            fail(error);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshEnd" object:nil];
            if(error.userInfo[@"com.alamofire.serialization.response.error.data"]){
            NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:&error];
                if (!self.filterError) {
                if (dic[@"errors"]&&[dic[@"errors"] isKindOfClass:[NSArray class]]&&dic[@"errors"][0][@"message"]) {
                    [SVProgressHUD showErrorWithStatus:dic[@"errors"][0][@"message"]];
                }else if ([dic isKindOfClass:[NSDictionary class]]&&dic[@"error"]) {
                    [SVProgressHUD showErrorWithStatus:dic[@"error"]];
                }
                }
            }else if (error.userInfo[@"NSLocalizedDescription"]&&!self.filterError){
                [SVProgressHUD showErrorWithStatus:error.userInfo[@"NSLocalizedDescription"]];
            }
            
        }
    }];
    }
}
-(void)postRequestWithBlock:(requestSuccetionActionBlock)success andFail:(nonnull requestSuccetionActionBlock)fail{
    [self postRequestWithlocalSuccessBlock:nil Block:^(id  _Nonnull obj) {
        if (success) {
            success(obj);
        }
    } andFail:fail];
}
-(void)formDataRequestWithBlock:(requestSuccetionActionBlock)success andFail:(nonnull requestSuccetionActionBlock)fail{
    [self formDataRequestWithlocalSuccessBlock:nil Block:success andFail:fail];
}
-(void)formDataRequestWithlocalSuccessBlock:(requestSuccetionActionBlock)localSuccess Block:(requestSuccetionActionBlock)success andFail:(nonnull requestSuccetionActionBlock)fail{
    requestSuccetionActionBlock successBlock = success;
    NSString *urlStr;
    if ([self.urlPath isUrl]) {
        urlStr = self.urlPath;
    }else{
        if (self.urlPath) {
            urlStr = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl],self.urlPath];
        }else{
            urlStr =[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl];
        }
    }
    
    if (localSuccess) {
    NSArray * arr= [self getLocalCache];
    FCUrlLocalModel *model =arr.firstObject;
    if (model.data) {
        id responseObj = [NSDictionary getDicWithData:model.data];
        id result = nil;
        result = [NSDictionary changeType:responseObj];
        if (localSuccess) {
            if(self.requestStrMJClass.length>0){
                NSArray *arr = [self.requestStrMJClass componentsSeparatedByString:@","];
                for (NSString *str in arr) {
                    if (!result) {
                        localSuccess(nil);
                        WJCLog(@"❌❌'%@'❌❌",str);
                        break;
                    }
                    if ([result isKindOfClass:[NSArray class]]) {
                        result = result[[str integerValue]];
                    }else{
                        result = result[str];
                    }
                }
                
                if ([result isKindOfClass:[NSArray class]]) {
                    if (self.mjClass) {
                        localSuccess([[self.mjClass class] mj_objectArrayWithKeyValuesArray:result]);
                    }else{
                        localSuccess(result);
                    }
                    
                }else{
                    if (self.mjClass) {
                        localSuccess([[self.mjClass class] mj_objectWithKeyValues:result]);
                    }else{
                        localSuccess(result);
                    }
                }
                
            }else{
                if (self.mjClass) {
                    localSuccess([[self.mjClass class] mj_objectWithKeyValues:result]);
                }else{
                    localSuccess(result);
                }
            }
        }
    }
    }
    if (successBlock) {
        
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    //检查地址中是否有中文
    urlStr = [NSURL URLWithString:urlStr] ? urlStr : [self strUTF8Encoding:urlStr];
    NSMutableDictionary *requestData = [NSMutableDictionary dictionaryWithDictionary:self.requestData];

    AFHTTPSessionManager *manager = [self getAFManager];
        if([self isKindOfClass:[UIButton class]]){
            ((UIButton*)self).enabled = NO;
        }
        [manager POST:urlStr parameters:requestData.count>0?requestData:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                

            } progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable obj) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                    if([self isKindOfClass:[UIButton class]]){
                        ((UIButton*)self).enabled = YES;
                    }
                });
                if (self.notJson) {
                    if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
                        NSDictionary *dic = @{
                            @"url":urlStr,
                            @"requestData":requestData.printfJson,
                            @"reponse": [[NSString alloc] initWithData:obj encoding:NSUTF8StringEncoding]
                        };
                        WJCLog(@"requestPrint:%@",dic.logParagraph);
                        
                    }
                    if (success) {
                        success(obj);
                        return;
                    }
                }
                obj = [NSDictionary changeType:obj];
                if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
                    NSDictionary *dic = @{
                        @"url":urlStr,
                        @"requestData":requestData.printfJson,
                        @"reponse":((NSDictionary*)obj).printfJson
                    };
                    WJCLog(@"requestPrint:%@",dic.logParagraph);
                    
                }
                 if ([obj[@"status"] integerValue]!=0&&[obj[@"status"] integerValue]!=200&&obj[@"msg"]) {
//                     if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
//                         NSDictionary *dic = @{
//                             @"url":urlStr,
//                             @"requestData":requestData.printfJson,
//                             @"reponse":((NSDictionary*)obj).printfJson
//                         };
//                         WJCLog(@"requestPrint:%@",dic.logParagraph);
//                     }
                     if (!self.filterError) {
                         [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",obj[@"msg"]]];
                         if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]){
                             [FCAlertToastView showFailWithStatus:[NSString stringWithFormat:@"%@\n\nURL:%@ head:%@\ndata:%@",obj[@"msg"],urlStr,manager.requestSerializer.HTTPRequestHeaders,requestData] andInputEnable:NO];
                         }
                     }
                     [obj checkErrorStatus:[obj[@"code"] integerValue]];
                     if (fail) {
                         fail(obj);
                     }
                     return;
                 }
                 
                 if (success) {
                     if (obj) {
                         [self saveLocalSaveWithRespon:obj];
                                }
                     if(self.requestStrMJClass.length>0){
                         NSArray *arr = [self.requestStrMJClass componentsSeparatedByString:@","];
                         id object = [obj skipGraphQLItems];
                         for (NSString *str in arr) {
                             if (!object) {
                                 success(nil);
                                 WJCLog(@"❌❌NSObject+KVCChangeType中requestClick数据找不到'%@'❌❌",str);
                                 break;
                             }
                             if ([object isKindOfClass:[NSArray class]]) {
                                 object = object[[str integerValue]];
                             }else{
                                 object = object[str];
                             }
                         }
                         if ([object isKindOfClass:[NSArray class]]) {
                             if (self.mjClass) {
                                 NSArray *arr =[[self.mjClass class] mj_objectArrayWithKeyValuesArray:object];
                                 success(arr);
                             }else{
                                 success(object);
                             }
                             
                         }else{
                             if (self.mjClass) {
                                 id obj =[[self.mjClass class] mj_objectWithKeyValues:object];
                                 success(obj);
                             }else{
                                 success(object);
                             }
                         }
                         
                     }else{
                         successBlock(obj);
                     }
                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                         [self upRequestDataBaseWithSuccess:((NSDictionary*)obj).printfJson andError:nil];
                         [[NSNotificationCenter defaultCenter] postNotificationName:self.urlPath object:nil];
                     });
                 }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if([self isKindOfClass:[UIButton class]]){
                    ((UIButton*)self).enabled = YES;
                }
                if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]){
                    [FCAlertToastView showFailWithStatus:[NSString stringWithFormat:@"URL:%@\n\n head:%@\ndata:%@",manager.requestSerializer.HTTPRequestHeaders,urlStr,requestData] andInputEnable:NO];
                }
                if (fail) {
                    fail(error);
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshEnd" object:nil];
                    if(error.userInfo[@"com.alamofire.serialization.response.error.data"]){
                    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:&error];
                        if(!self.filterError){
                        if (dic[@"errors"]&&[dic[@"errors"] isKindOfClass:[NSArray class]]&&dic[@"errors"][0][@"message"]) {
                            [SVProgressHUD showErrorWithStatus:dic[@"errors"][0][@"message"]];
                        }else if ([dic isKindOfClass:[NSDictionary class]]&&dic[@"error"]) {
                            [SVProgressHUD showErrorWithStatus:dic[@"error"]];
                        }else{
                            [SVProgressHUD showErrorWithStatus:@"UnKnow errors"];
                    }
                        }
                    }else if (error.userInfo[@"NSLocalizedDescription"]&&!self.filterError){
                        [SVProgressHUD showErrorWithStatus:error.userInfo[@"NSLocalizedDescription"]];
                    }
                    
                }
            }];
    }
}
///优先走缓存请求
-(void)postPriorityRequestWithBlock:(requestSuccetionActionBlock)success{
    NSString *urlStr;
    if ([self.urlPath isUrl]) {
        urlStr = self.urlPath;
    }else{
        if (self.urlPath) {
            urlStr = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl],self.urlPath];
        }else{
            urlStr =[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl];
        }
    }
    NSArray * arr= [self getLocalCache];
    FCUrlLocalModel *model =arr.firstObject;
    if (model.data) {
        id responseObj = [NSDictionary getDicWithData:model.data];
        id result = nil;
        result = [NSDictionary changeType:responseObj];
        if (success) {
            if(self.requestStrMJClass.length>0){
                NSArray *arr = [self.requestStrMJClass componentsSeparatedByString:@","];
                for (NSString *str in arr) {
                    if (!result) {
                        success(nil);
                        WJCLog(@"❌❌'%@'❌❌",str);
                        break;
                    }
                    if ([result isKindOfClass:[NSArray class]]) {
                        result = result[[str integerValue]];
                    }else{
                        result = result[str];
                    }
                }
                
                if ([result isKindOfClass:[NSArray class]]) {
                    if (self.mjClass) {
                        success([[self.mjClass class] mj_objectArrayWithKeyValuesArray:result]);
                    }else{
                        success(result);
                    }
                    
                }else{
                    if (self.mjClass) {
                        success([[self.mjClass class] mj_objectWithKeyValues:result]);
                    }else{
                        success(result);
                    }
                }
                
            }else{
                if (self.mjClass) {
                    success([[self.mjClass class] mj_objectWithKeyValues:result]);
                }else{
                    success(result);
                }
            }
        }
    }
        [self postRequestWithBlock:success andFail:^(id  _Nonnull obj) {
            
//        }]//formDataRequestWithlocalSuccessBlock:nil Block:success andFail:^(id  _Nonnull obj) {
            
        }];
}



-(void)uploadFileWithFile:(id)file andFileType:(INFIUploadType)type Block:(requestSuccetionActionBlock)success{
    NSData *data = nil;
    if ([file isKindOfClass:[UIImage class]]) {
        UIImage *img =file;
        if (type == INFIUploadTypeJPGImg) {
            data = UIImageJPEGRepresentation(img,1);
        }else{
        UIImage *image= [UIImage scaleImage:img toScale:0.5];
        data = UIImagePNGRepresentation(image);
        }
    }else if([file isKindOfClass:[NSData class]]) {
        data = file;
    }else if([file isKindOfClass:[UIImage class]]) {
    }else if([file isKindOfClass:[UIImage class]]) {
    }
    NSString *url = [NSString stringWithFormat:@"%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployUploadImageUrl]];
    NSString *ext;
    NSString *mimeType;
    switch (type) {
        case INFIUploadTypeImg:
            ext = @".png";
            mimeType = @"image/png";
            break;
        case INFIUploadTypeJPGImg:
            ext = @".jpg";
            mimeType = @"image/jpg";
            break;
        case INFIUploadTypeVideo:
            ext = @".mp4";
            mimeType = @"video/mp4";
            break;
        case INFIUploadTypeVoice:
            ext = @".AAC";
            mimeType = @"audio/aac";
        default:
            ext = @"";
            mimeType = @"text/html";
            break;
    }
    
    [[self getAFManager] POST:url parameters:@{@"file":@""} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        [formatter setDateFormat:@"YYYYMMddHHmmss"];
        NSDate *datenow = [NSDate date];
        NSString *currentTimeString = [formatter stringFromDate:datenow];
        NSString * timeStr = [NSString stringWithFormat:@"%@-%@",currentTimeString,ext];
        
        [formData appendPartWithFileData:data name:@"file" fileName:timeStr mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //Update the progress view
            if (!self.filterError) {
                [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"uploading"];
            }
           
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable obj) {
        if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
            NSDictionary *dic = @{
                @"url":url,
                @"requestData":@"upload",
                @"reponse":((NSDictionary*)obj).printfJson
            };
            WJCLog(@"requestPrint:%@",dic.logParagraph);
        }
        if ([obj[@"status"] integerValue]!=0&&obj[@"msg"]) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",obj[@"msg"]]];
            [obj checkErrorStatus:[obj[@"code"] integerValue]];
            return;
        }else{
            [SVProgressHUD dismiss];
            if (success) {
                success(obj[@"data"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"上传失败"];
    }];
    
}

-(void)uploadFileWithFiles:(NSMutableArray<upLoadModel *> *)files Block:(requestSuccetionActionBlock)success{
    for (int i = 0; i <files.count; i++) {
        if (files[i].data.length>0) {
            continue;
        }else{
            switch (files[i].uploadType) {
                case INFIUploadTypeImg:{
                    if (files[i].img) {
                        UIImage *image= [UIImage scaleImage:files[i].img toScale:0.5];
                        files[i].data = UIImagePNGRepresentation(image);
                    }else if(files[i].filePath){
                        files[i].data = [NSData dataWithContentsOfFile:files[i].filePath];
                    }
                }
                    break;
                default:
                {
                    if(files[i].filePath){
                        files[i].data = [NSData dataWithContentsOfFile:files[i].filePath];
                    }
                }
                    break;
            }
        }
    }
    NSString *url = [NSString stringWithFormat:@"%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployUploadImageUrls]];
    
    
    AFHTTPSessionManager *manager = [self getAFManager];
    [manager POST:url parameters:@{@"files":@""} headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i <files.count; i++) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            
            [formatter setDateFormat:@"YYYYMMddHHmmss"];
            NSDate *datenow = [NSDate date];
            NSString *currentTimeString = [formatter stringFromDate:datenow];
            NSString * timeStr = [NSString stringWithFormat:@"%@-%@",currentTimeString,files[i].ext];
            [formData appendPartWithFileData:files[i].data name:@"files" fileName:timeStr mimeType:files[i].mimeType];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            //Update the progress view
            [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"uploading"];
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable obj) {
        if ([[WJCDeployModel getDeployWithDeployKey:WJCDeployEnv] isEqual:@"dev"]) {
            NSDictionary *dic = @{
                @"url":url,
                @"requestData":@"upload",
                @"reponse":((NSDictionary*)obj).printfJson
            };
            WJCLog(@"requestPrint:%@",dic.logParagraph);
        }
        if ([obj[@"code"] integerValue]!=0&&obj[@"msg"]) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",obj[@"msg"]]];
            [obj checkErrorStatus:[obj[@"code"] integerValue]];
            return;
        }else{
            [SVProgressHUD dismiss];
            if (success) {
                success(obj[@"data"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"上传失败"];

    }];
}
-(void)checkErrorStatus:(NSInteger)status{
    if (status ==10) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [FCUserDefaults removeObjectForKey:@"token"];
            [saveSandBox deleteAllObjectWithCookie:YES];
            
        });
    }
}

- (NSString *)strUTF8Encoding:(NSString *)str{
    
    return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


/**
 AFHTTPSessionManager配置请求格式
 
 @return 返回配置好的AFHTTPSessionManager
 */
-(AFHTTPSessionManager *)getAFManager{
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
   
    if (self.notJson) {
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //设置返回NSData 数据
    }else{
        manager.responseSerializer = [AFJSONResponseSerializer serializer];//设置返回数据为json
    }
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置返回NSData 数据
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:200];
    if ([FCUserDefaults objectForKey:@"token"]) {
        //        [requestData setValue:[FCUserDefaults objectForKey:@"token"] forKeyPath:@"token"];
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@",[FCUserDefaults objectForKey:@"token"]] forHTTPHeaderField:@"Authorization"];
        
    }
    NSArray *array = [saveSandBox getCookie];
    
    if (array&&array.count>0) {
        NSMutableString *str=[NSMutableString new];
        for (NSHTTPCookie *cookie in array) {

            [str appendString:[NSString stringWithFormat:@"%@=%@;",cookie.name,cookie.value]];
            if([cookie.name isEqual:@"JSESSIONID"]){
                [str appendString:[NSString stringWithFormat:@"%@=%@;",@"shop_cookies",cookie.value]];
            }
            
        }
        
        [manager.requestSerializer setValue:str forHTTPHeaderField:@"Cookie"];
    }
    
    [manager.requestSerializer setValue:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] forHTTPHeaderField:@"AppVersion"];
    NSString *newUserAgent = [NSString getNewUserAgent];
    [manager.requestSerializer setValue:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"UserAgent"] forHTTPHeaderField:newUserAgent];
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    manager.requestSerializer.timeoutInterval = 45;
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"]){
        [manager.requestSerializer setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"] forHTTPHeaderField:@"Accept-Language"];
    }else{
        [manager.requestSerializer setValue:[FCUserDefaults objectForKey:@"appLanguage"]?[FCUserDefaults objectForKey:@"appLanguage"]:@"zh-cn" forHTTPHeaderField:@"Accept-Language"];
    }
    [manager.requestSerializer setValue:@"false" forHTTPHeaderField:@"useClientLang"];
    
    
    
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"text/xml",
                                                                              @"image/*"]];
    
    [manager.requestSerializer setValue:@"Code=iOS" forHTTPHeaderField:@"Client-Info"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Platform=iOS;VersionName=%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"client-msg"];
    
    return manager;
    
}
-(NSArray*)getLocalCache{
    NSString *urlStr;
    if ([self.urlPath isUrl]) {
        urlStr = self.urlPath;
    }else{
        if (self.urlPath) {
            urlStr = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl],self.urlPath];
        }else{
            urlStr =[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl];
        }
    }
    NSMutableArray *arr = [NSMutableArray new];
    if (urlStr) {
        [arr addObject:urlStr];
    }
    for (NSString*key in self.requestData) {
        [arr addObject:[NSString stringWithFormat:@"%@-%@",key,self.requestData[key]]];
    }
    NSArray * array= [saveSandBox getDataBaseWithClass:[FCUrlLocalModel class] andLimitType:[NSString stringWithFormat:@"id='%@'",[arr componentsJoinedByString:@"/"]]];
    return array;
}
-(void)saveLocalSaveWithRespon:(NSDictionary*)obj{
    if (obj) {
        NSString *urlStr;
        if ([self.urlPath isUrl]) {
            urlStr = self.urlPath;
        }else{
            if (self.urlPath) {
                urlStr = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl],self.urlPath];
            }else{
                urlStr =[WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl];
            }
        }
        NSMutableArray *arr = [NSMutableArray new];
        if (urlStr) {
            [arr addObject:urlStr];
        }
        for (NSString*key in self.requestData) {
            [arr addObject:[NSString stringWithFormat:@"%@-%@",key,self.requestData[key]]];
        }
                   FCUrlLocalModel *model = [[FCUrlLocalModel alloc] init];
                   model.data =obj;
                   model.Id = [arr componentsJoinedByString:@"/"];
                   [saveSandBox saveDataBaseClass:[FCUrlLocalModel class] andObject:model orType:@"POST" andOther:nil];
               }
}
@end
